package com.linsen.core.web.interceptor;

import com.linsen.core.common.constant.AuthConstant;
import com.linsen.core.common.constant.LinsenConstant;
import com.linsen.core.common.context.TokenContextHolder;
import com.linsen.core.common.context.TraceContextHolder;
import com.linsen.core.common.util.SecurityUtil;
import com.linsen.core.common.util.TraceUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * @author zhaoyong
 * @date 2023/03/02
 */
@Slf4j
public class RequestInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        final String traceId = request.getHeader(LinsenConstant.LINSEN_TRACE_ID);
        final String token = Optional.ofNullable(SecurityUtil.getHeaderToken(request)).orElse(SecurityUtil.getQueryToken(request));
        TraceUtil.mdcTraceId(traceId);
        TraceContextHolder.setTraceId(traceId);
        log.debug("request interceptor set trace id:{}", traceId);
        TokenContextHolder.setToken(token);
        log.debug("request interceptor set token:{}", token);
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
        TraceContextHolder.removeTraceId();
        log.debug("request interceptor remove trace id");
        TokenContextHolder.removeToken();
        log.debug("request interceptor remove token");
    }
}
